// VR影院监控页面逻辑：设备状态和影片加载进度
(function () {
    var isLoading = false;
    
    // 更新设备使用状态
    function updateDeviceStatus() {
        if (isLoading) return;
        isLoading = true;
        
        showLoadingState('device');
        
        apiService.getVRDeviceStatus()
            .then(function (data) {
                console.log('设备状态数据:', data);
                
                // 更新各个设备状态
                if (data.devices) {
                    data.devices.forEach(function(device, index) {
                        updateDeviceInfo('device' + (index + 1), device);
                    });
                } else {
                    // 兼容旧格式
                    updateDeviceInfo('device1', data.device1 || data.device_1);
                    updateDeviceInfo('device2', data.device2 || data.device_2);
                    updateDeviceInfo('device3', data.device3 || data.device_3);
                    updateDeviceInfo('device4', data.device4 || data.device_4);
                }
                
                hideLoadingState('device');
            })
            .catch(function (err) {
                console.error('获取设备状态失败:', err);
                hideLoadingState('device');
                showDeviceError();
            })
            .finally(function() {
                isLoading = false;
            });
    }
    
    function updateDeviceInfo(deviceId, data) {
        if (!data) return;
        
        var status = data.status || 'idle';
        var lastUpdate = data.lastUpdate || data.last_update || new Date().toISOString();
        var timeAgo = getTimeAgo(lastUpdate);
        
        var statusEl = document.getElementById(deviceId + 'Status');
        var timeEl = document.getElementById(deviceId + 'Time');
        
        if (statusEl) {
            statusEl.textContent = getDeviceStatusText(status);
            statusEl.className = 'status-indicator ' + status;
        }
        
        if (timeEl) {
            timeEl.textContent = timeAgo;
        }
    }
    
    function getDeviceStatusText(status) {
        switch (status) {
            case 'idle': return '空闲';
            case 'in_use': return '使用中';
            case 'maintenance': return '维护中';
            case 'error': return '故障';
            case 'offline': return '离线';
            default: return '未知';
        }
    }
    
    // 更新所有设备的播放影片和片段加载状态
    function updateAllDeviceMovies() {
        apiService.getCurrentMovie()
            .then(function (data) {
                console.log('所有设备播放影片数据:', data);
                
                // 更新每个设备的影片信息
                if (data.devices) {
                    data.devices.forEach(function(deviceData, index) {
                        var deviceId = 'device' + (index + 1);
                        updateDeviceMovieInfo(deviceId, deviceData);
                    });
                } else {
                    // 兼容旧格式，假设只有一个设备
                    updateDeviceMovieInfo('device1', data);
                }
            })
            .catch(function (err) {
                console.error('获取设备播放影片失败:', err);
                showAllDeviceMovieError();
            });
    }
    
    // 更新单个设备的影片信息
    function updateDeviceMovieInfo(deviceId, data) {
        if (!data) return;
        
        var movieNameEl = document.getElementById(deviceId + 'MovieName');
        var movieStatusEl = document.getElementById(deviceId + 'MovieStatus');
        var playTimeEl = document.getElementById(deviceId + 'PlayTime');
        
        // 更新影片名称
        if (movieNameEl && data.movieName) {
            movieNameEl.textContent = data.movieName;
        }
        
        // 更新影片状态
        if (movieStatusEl) {
            var status = data.status || 'playing';
            movieStatusEl.textContent = getMovieStatusText(status);
            movieStatusEl.className = 'status-badge ' + status;
        }
        
        // 更新播放时间
        if (playTimeEl && data.playTime) {
            playTimeEl.textContent = data.playTime;
        }
        
        // 更新片段加载状态
        if (data.segments) {
            data.segments.forEach(function(segment, index) {
                updateDeviceSegmentProgress(deviceId + 'Segment' + (index + 1), segment);
            });
        }
    }
    
    // 更新设备片段加载进度
    function updateDeviceSegmentProgress(segmentId, data) {
        if (!data) return;
        
        var progress = data.progress || 0;
        var status = data.status || 'loading';
        
        var progressEl = document.getElementById(segmentId + 'Progress');
        var statusEl = document.getElementById(segmentId + 'Status');
        
        if (progressEl) {
            progressEl.style.width = progress + '%';
            progressEl.className = 'progress-fill';
            
            if (progress >= 100) {
                progressEl.className += ' completed';
            } else if (progress >= 80) {
                progressEl.className += ' almost-done';
            } else if (progress >= 50) {
                progressEl.className += ' half-done';
            }
        }
        
        if (statusEl) {
            statusEl.textContent = getSegmentStatusText(status);
            statusEl.className = 'status-text ' + status;
        }
    }
    
    // 获取影片状态文本
    function getMovieStatusText(status) {
        switch (status) {
            case 'playing': return '正在播放';
            case 'paused': return '已暂停';
            case 'stopped': return '已停止';
            case 'loading': return '加载中';
            case 'error': return '播放错误';
            default: return '未知状态';
        }
    }
    
    // 获取片段状态文本
    function getSegmentStatusText(status) {
        switch (status) {
            case 'loaded': return '已加载';
            case 'loading': return '加载中';
            case 'pending': return '等待中';
            case 'error': return '加载失败';
            default: return '未知';
        }
    }
    
    function getTimeAgo(timestamp) {
        var now = new Date();
        var time = new Date(timestamp);
        var diff = Math.floor((now - time) / 1000);
        
        if (diff < 60) return '刚刚';
        if (diff < 3600) return Math.floor(diff / 60) + '分钟前';
        if (diff < 86400) return Math.floor(diff / 3600) + '小时前';
        return Math.floor(diff / 86400) + '天前';
    }
    
    // 显示加载状态
    function showLoadingState(type) {
        if (type === 'device') {
            var cards = document.querySelectorAll('.device-status-card');
            cards.forEach(function(card) {
                card.classList.add('loading');
            });
        }
    }
    
    // 隐藏加载状态
    function hideLoadingState(type) {
        if (type === 'device') {
            var cards = document.querySelectorAll('.device-status-card');
            cards.forEach(function(card) {
                card.classList.remove('loading');
            });
        }
    }
    
    // 显示设备错误状态
    function showDeviceError() {
        var devices = ['device1', 'device2', 'device3', 'device4'];
        devices.forEach(function(device) {
            var statusEl = document.getElementById(device + 'Status');
            var timeEl = document.getElementById(device + 'Time');
            
            if (statusEl) {
                statusEl.textContent = '连接失败';
                statusEl.className = 'status-indicator error';
            }
            
            if (timeEl) {
                timeEl.textContent = '无法获取';
            }
        });
    }
    
    // 显示所有设备影片错误状态
    function showAllDeviceMovieError() {
        var devices = ['device1', 'device2', 'device3', 'device4'];
        
        devices.forEach(function(device) {
            var movieNameEl = document.getElementById(device + 'MovieName');
            var movieStatusEl = document.getElementById(device + 'MovieStatus');
            var playTimeEl = document.getElementById(device + 'PlayTime');
            
            if (movieNameEl) {
                movieNameEl.textContent = '无法获取影片信息';
            }
            
            if (movieStatusEl) {
                movieStatusEl.textContent = '连接失败';
                movieStatusEl.className = 'status-badge error';
            }
            
            if (playTimeEl) {
                playTimeEl.textContent = '--:--';
            }
            
            // 显示片段错误状态
            var segments = ['Segment1', 'Segment2', 'Segment3', 'Segment4'];
            segments.forEach(function(segment) {
                var progressEl = document.getElementById(device + segment + 'Progress');
                var statusEl = document.getElementById(device + segment + 'Status');
                
                if (progressEl) {
                    progressEl.style.width = '0%';
                    progressEl.className = 'progress-fill error';
                }
                
                if (statusEl) {
                    statusEl.textContent = '连接失败';
                    statusEl.className = 'status-text error';
                }
            });
        });
    }
    
    // 页面加载时开始监控
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            updateDeviceStatus();
            updateAllDeviceMovies();
            // 每5秒更新一次设备状态
            setInterval(updateDeviceStatus, 5000);
            // 每3秒更新一次所有设备的播放影片和片段状态
            setInterval(updateAllDeviceMovies, 3000);
        });
    } else {
        updateDeviceStatus();
        updateAllDeviceMovies();
        setInterval(updateDeviceStatus, 5000);
        setInterval(updateAllDeviceMovies, 3000);
    }
})();
